'use strict';

const Controller = require('egg').Controller;

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    ctx.body = 'https://eggjs.org/';
  }

  async getUser() {
    const { ctx, app } = this;
    const { user, type = 'all' } = ctx.query;

    try {
      if (user) {
        const payload = await app.redis.hgetall(user);
        if (payload.type === type || (payload.type && type === 'all')) {
          ctx.body = payload;
        } else {
          ctx.body = { code: '404', msg: '未查询到相应数据' };
        }
      } else {
        ctx.body = { code: '404', msg: '缺少必要参数' };
      }
    } catch (error) {
      ctx.body = { code: '404', msg: '后台服务出错' };
    }
  }

  async create() {
    const { ctx, app } = this;
    const { body } = ctx.request;
    await app.redis.expire(body.owner, 3600);
    for (const key in body) {
      await app.redis.hmset(body.owner, key, body[key]);
    }
    ctx.body = await app.redis.hgetall(body.owner);
  }
}

module.exports = HomeController;
